import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_svg/flutter_svg.dart';
import '../../utils.dart';

export 'PageDataMixin.dart';

@optionalTypeArgs
abstract class PageQueryListState<T extends StatefulWidget> extends State<T> {
  /// 是否使用 Sliver， 在 initState 中设为false，appBar 将没有Sliver的效果
  bool useSliver = true;


  ListViewState _state;
  ListViewState get listState => getListState();

  ListViewState getListState() {
    if (_state == null)
      _state = ListViewState();
    return _state;
  }

  @override
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: useSliver ? null : buildAppBar(context),
      body: StoreBuilder<SysState>(
        builder: (context, store) {
          return buildBodyView();
      })
    );
  }

  /// 标题
  Widget get title => getTitle();
  /// 副标题
  String get subTitle => getSubTitle();
  /// 数据长度
  int get dataLength => getDataLength();
  /// 数据是否加载
  bool get dataIsNull => getDataIsNull();
  /// 是否还能加载更多
  bool get allowLoadMore => getAllowLoadMore();

  @protected
  //@mustCallSuper
  int getDataLength();
  /// 获取标题
  @protected
  //@mustCallSuper
  Widget getTitle();
  /// 获取副标题
  @protected
  String getSubTitle() {
    return null;
  }

  @protected
  bool getDataIsNull();

  @protected
  bool getAllowLoadMore() {
    return listState.currentPage >= listState.totalPage;
  }

  double getExpandedHeight() {
    return 104.0;
  }

  bool buildAppBarPinned() {
    return  false;
  }

  bool buildAppBarFloating() {
    return true;
  }

  bool buildAppBarSnap() {
    return true;
  }

  Widget buildBodyView() {
    if (useSliver)
      return NestedScrollView(
          controller: listState.controller,
          headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
            return [
              buildAppBar(context),
            ];
          },
          body: buildBody()
      );
    return buildBody();
  }

  Widget buildBody() {
    return listState.isWait && !listState.isLoadMore ?
      Center(child: CircularProgressIndicator(strokeWidth: 2.0)) :
      dataLength == 0 ? buildEmptyHintView(context) : Container(child: buildListWidget());
  }

  @protected
  buildAppBar(BuildContext context) {
    if (useSliver)
      return SliverAppBar(
        title: Common.buildAppBarTitle(title, subTitle),
        centerTitle: true,
        expandedHeight: useSliver ? getExpandedHeight() : 0.0,
        iconTheme: IconThemeData(color: Colors.white),
        pinned: useSliver ? buildAppBarPinned() : true,
        floating: useSliver ? buildAppBarFloating() : false,
        snap: useSliver ? buildAppBarSnap() : false,
        leading: buildLeading(),
        actions: buildHeaderActions(),
        flexibleSpace: useSliver ? buildFlexibleSpace(context) : null,
        elevation: Styles.elevation,
        bottom: buildAppBarBottom(context),
      );
    return AppBar(
      title: Common.buildAppBarTitle(title, subTitle),
      centerTitle: true,
      iconTheme: IconThemeData(color: Colors.white),
      actions: buildHeaderActions(),
      leading: buildLeading(),
      flexibleSpace: useSliver ? buildFlexibleSpace(context) : null,
      elevation: Styles.elevation,
      bottom: buildAppBarBottom(context),
    );
  }

  @protected
  List<Widget> buildHeaderActions() {
    return null;
  }

  @protected
  Widget buildFilterView(BuildContext context) {
    return Row(
        children: <Widget>[]
    );
  }

  @protected
  Widget buildLeading() {
    return null;
  }

  @protected
  buildAppBarBottom(BuildContext context) {
    return null;
  }

  /// 加载数据
  @protected
  //@mustCallSuper
  Future<bool> doRefresh(bool isReLoad, {bool setWait = true}) async {
    if (setWait) {
      setState(() {
        listState.isWait = true;
      });
    }

    return true;
  }

  Widget buildFlexibleSpace(BuildContext context) {
    return FlexibleSpaceBar(
      background: Container(
        margin: EdgeInsets.only(top: Utils.getSysStatsHeight(this.context) + kToolbarHeight),
        child: buildFilterView(context),
      ),
    );
  }

  Widget buildListWidget() {
    return NotificationListener(
      onNotification: (Notification ntf) {
        if (ntf is OverscrollNotification) {
          if (!listState.isWait && !listState.isLoadMore) {
            listState.isLoadMore = true;
            if (!allowLoadMore) {
              setState(() {
                listState.isWait = false;
                listState.isLoadMore = false;
              });
              return true;
            }
            if (Consts.debug) print("loading more, ${listState.currentPage}/${listState.totalPage}");
            setState(() {
              listState.currentPage++;
            });
            doRefresh(false);
          }
        }
        return true;
      },
      child: RefreshIndicator(
          child:  buildListView(),
          onRefresh: () async {
            await doRefresh(true, setWait: false);
          }
      ),
    );
  }

  Widget buildListView() {
    return CustomScrollView(
      controller: useSliver ? null : listState.controller,
      slivers: <Widget>[
        SliverList(
          delegate: SliverChildBuilderDelegate(
            buildListViewItem,
            childCount: dataLength + 1,
          ),
        )
      ],
    );
  }

  Widget buildListViewItem(BuildContext context, int index) {
    if (index >= dataLength) {
      return buildListFooterView(context);
    }

    return buildListItemViewIndex(context, index);
  }

  Widget buildEmptyHintView(BuildContext context) {
    return Container(
      width: double.infinity,
      alignment: Alignment.center,
      child: InkWell(
        child: Center(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              SvgPicture.asset("assets/images/empty.svg", width: 100.0, height: 100.0),
              SizedBox(height: 8.0),
              //Icon(Icons.insert_emoticon, size: 50.0, color: Styles.fontColorHintLight),
              Text(Utils.getLocale(context).list_empty, style: Styles.smallSubLightText)
            ],
          ),
        ),
        onTap: () {
          doRefresh(true);
        },
      ),
    );
  }

  @protected
  buildListFooterView(BuildContext context) {
    return Container(
      color: Styles.mainBackgroundColor, height: 80.0,
      alignment: Alignment.center,
      child: IconText(text: !allowLoadMore && (!listState.isWait && !listState.isLoadMore) ?
      sprintf(Utils.getLocale(context).listLoadFinish, [dataLength]):
      listState.total > 0 ? sprintf(Utils.getLocale(context).listLoadingTip, [dataLength, listState.total]) : sprintf(Utils.getLocale(context).listLoadingTip2, [dataLength]), style: Styles.minSubLightText,
        icon: Icon(Icons.sentiment_satisfied, size: Styles.textMinSize, color: Styles.subLightTextColor),
        bgcolor: Styles.mainBackgroundColor,
        useWrap: true,
      ),
    );
  }


  // 生成消息列表项
  @protected
  Widget buildListItemViewIndex(BuildContext context, int index) {
    return Text("Error");
  }

  @override
  void initState() {
    super.initState();
    init();
  }

  /// 初始化一些数据
  init() async {
    if (dataIsNull) {
      listState.isWait = true;
      doRefresh(true, setWait: true);
    }
  }
}

/// 列表数据页状态
class ListViewState {
  final ScrollController controller;
  ListViewState({this.controller});
  bool isWait = false;
  bool isLoadMore = false;
  int currentPage = 1; // 已经加载的页数
  int totalPage = 1;  // 总页数
  int total = 0;  // 数据总数
  int pageSize = 10; // 每次加载的条数
}